﻿namespace JobButenko.Controllers
{
    using System.IO;
    using System.Web.Mvc;

    using JobButenko.Models.BusinessLogicLayer;

    public class CandidateController : Controller
    {
        // GET: /Candidate/
        private readonly DataManager dataManager;

        public CandidateController(DataManager dataManager)
        {
            this.dataManager = dataManager;
        }

        public ActionResult ViewCandidateInfo(int id)
        {
            ViewData.Model = this.dataManager.Candidate.GetCandidateFromId(id);
            return View();
        }

        public ActionResult GetAddCandidateVacancy()
        {
            ViewData.Model = this.dataManager.EmployedJob.GetAddCandidateVacancy();
            return View();
        }

        [HttpPost]
        public ActionResult UploadResumeDoc()
        {
            foreach (string inputTagName in Request.Files)
            {
                var file = Request.Files[inputTagName];
                if (file == null
                    ||
                    (!file.FileName.EndsWith(".doc") && !file.FileName.EndsWith(".docx")
                     && !file.FileName.EndsWith(".rtf")))
                {
                    continue;
                }

                if (file.ContentLength <= 0)
                {
                    continue;
                }

                var docId = this.dataManager.Candidate.GetCandidateFromUserName(User.Identity.Name).ResumeDocId;
                var resumeDocId = docId == null
                                      ? this.dataManager.ResumeDoc.UploadDoc(file)
                                      : this.dataManager.ResumeDoc.UpdateResumeDoc((int)docId, file);
                this.dataManager.Candidate.UpdateCandidateDoc(resumeDocId, User.Identity.Name);
            }

            return RedirectToAction("ViewResume", "Resume");
        }

        public ActionResult Download(int id)
        {
            var candidate = this.dataManager.Candidate.GetCandidateFromResDocId(id);
            var resumeDoc = this.dataManager.ResumeDoc.GetByteResumeDoc(id);
            var fileStream = new MemoryStream(resumeDoc);

            return File(fileStream, "application/msword", candidate.Name + " " + candidate.Surname + "(резюме)");
        }

        public ActionResult DeleteFile(int id, int candidateId)
        {
            this.dataManager.Candidate.DeleteCandidateDoc(candidateId);
            this.dataManager.ResumeDoc.DeleteResumeDoc(id);
            return RedirectToAction("ViewResume", "Resume");
        }

    }
}
